package eg.edu.eelu.fyp2013.jdetector.gui;

import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import com.mathworks.toolbox.javabuilder.MWException;

import matlabcontrol.MatlabConnectionException;
import eg.edu.eelu.fyp2013.jdetector.core.Enhancement.Enhance;
import eg.edu.eelu.fyp2013.jdetector.core.classifier.NerualNetworkClassifier;
import eg.edu.eelu.fyp2013.jdetector.core.classifier.UserClassification;
import eg.edu.eelu.fyp2013.jdetector.core.input_output.AMatrix;
import eg.edu.eelu.fyp2013.jdetector.core.input_output.ClassiferData;
import eg.edu.eelu.fyp2013.jdetector.core.input_output.FeatureExtraction;
import eg.edu.eelu.fyp2013.jdetector.core.input_output.LoadData;
import eg.edu.eelu.fyp2013.jdetector.core.swt.ReducePCANeural;
import eg.edu.eelu.fyp2013.jdetector.core.swt.ReductionDeminsion_PCA;
import eg.edu.eelu.fyp2013.jdetector.core.swt.swtFExtraction;

public class UserInterfaceJDetector extends JFrame {



	private static final class ImagedPanel extends JPanel {
		public Image image = null;

		@Override
		protected void paintComponent(Graphics g) {
			super.paintComponent(g);
			if (image!=null) {
				g.drawImage(image, 0, 0,this.getWidth(),this.getHeight(), this);
			}
		}
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private BufferedImage SamplePreviewImage;
	private JPanel contentPane;


	/**
	 * Launch the application.
	 */
	AMatrix DataMatrix;
	ArrayList<AMatrix> TestDataMatixList = new ArrayList<AMatrix>();
	ArrayList<AMatrix> inputDataMatixList = new ArrayList<AMatrix>();
	ArrayList<AMatrix> learnMedMatixList = new ArrayList<AMatrix>();

	ArrayList<AMatrix> testMedMatixList = new ArrayList<AMatrix>();

	ArrayList<FeatureExtraction> learnFeaturedMatixList = new ArrayList<FeatureExtraction>();
	ArrayList<FeatureExtraction> testFeaturedMatixList = new ArrayList<FeatureExtraction>();

	ArrayList<ArrayList<FeatureExtraction>> levelswtFeaturedMatixList = new ArrayList<ArrayList<FeatureExtraction>>();
	//ArrayList<ArrayList<FeatureExtraction>> leveltestFeaturedMatixList = new ArrayList<ArrayList<FeatureExtraction>>();

	ClassiferData [] FinalUsertestfeatures;
	ClassiferData [] FinalNeurallearnfeatures;
	ClassiferData[] neuralClassifyData ;
	final JTextArea resultTextArea = new JTextArea();
	final DefaultListModel<String> model = new DefaultListModel<String>();
	final JList<String> folderList = new JList<String>(model);
	final JScrollPane scrollPane = new JScrollPane(folderList);
	final ImagedPanel previewPanel = new ImagedPanel();


	public static void main(String[] args) throws MatlabConnectionException{




		////
		try {
			// Set System L&F
			UIManager.setLookAndFeel(
					UIManager.getSystemLookAndFeelClassName());
		} 
		catch (UnsupportedLookAndFeelException e) {
			// handle exception
		}
		catch (ClassNotFoundException e) {
			// handle exception
		}
		catch (InstantiationException e) {
			// handle exception
		}
		catch (IllegalAccessException e) {
			// handle exception
		}

		//   new SwingApplication(); //Create and show the GUI.

		////
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					UserInterfaceJDetector frame = new UserInterfaceJDetector();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 * @throws MatlabConnectionException 
	 */
	public UserInterfaceJDetector()  {
		setResizable(false);
		setTitle("JDetector");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(300, 10, 713, 550);

		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		JMenu mnNewMenu = new JMenu("File");
		menuBar.add(mnNewMenu);

		JMenuItem mntmOpenFolder = new JMenuItem("Open folder");
		mntmOpenFolder.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser folderChoose = new JFileChooser();
				
				folderChoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				folderChoose.showOpenDialog(null);
				final String folderName = folderChoose.getSelectedFile().getPath();
				File folder = new File(folderName);
				final File[] listOfFiles = folder.listFiles();



				folderList.addListSelectionListener(
						new ListSelectionListener() {

							@Override
							public void valueChanged(ListSelectionEvent arg0) {

								File f = new File(folderName, folderList.getSelectedValue());
								final ImageIcon originalIcon = new ImageIcon(f.getPath());
//								BufferedImage destinationImage = new BufferedImage(previewPanel.getWidth(), previewPanel.getHeight(), BufferedImage.TYPE_INT_RGB);
//								destinationImage.getGraphics().drawImage(originalIcon.getImage(), 0, 0, panel_2.getWidth(), prevpanel_2.getHeight(), null);
////										previewImageLabel.setIcon(new ImageIcon(destinationImage));
								previewPanel.image=originalIcon.getImage();
								previewPanel.repaint();
							}
						});




				for (int i = 0; i < listOfFiles.length; i++) {
					if (listOfFiles[i].isFile()) {

						model.addElement(listOfFiles[i].getName());

						//fileNames[i] = listOfFiles[i].getName();

						//folderTextArea.append(listOfFiles[i].getName() + "\n");
						//previewLabel.setIcon(new ImageIcon(listOfFiles[i].getPath()));
						//String[] fileNames 
					}

				}
				
				final int listModelSize = folderList.getModel().getSize();
				if(listModelSize !=0){
					folderList.setSelectedIndex(0);
				}
			//	btnLoadFolderOf.setEnabled(listModelSize ==0);
				
				int filesNumber = listOfFiles.length;
				String loadedData = new String("The number of loaded files is: " + filesNumber);
				resultTextArea.append(loadedData + "\n");
				

				//model.addElement(fileNames);



				


				LoadData ld = new LoadData();
				AMatrix[] InputDataMatrix = null;
				InputDataMatrix = ld.loadInputdata(folderName);
				
				
				Enhance E = new Enhance();
				for(int k = 0; k < InputDataMatrix.length ; k++)
				{
					inputDataMatixList.add(InputDataMatrix[k]);
				}

				ArrayList<AMatrix> EnhancedDataMatrixlist  = E.ApplyEnhance(inputDataMatixList);

				//SWT

				
				ArrayList<FeatureExtraction> AllFeaturedMatixList = new ArrayList<FeatureExtraction>(); 
				
					swtFExtraction S = new swtFExtraction();
					int x = 3;
					for(int m = 0; m <  x; m++){
						


							if(EnhancedDataMatrixlist.size() > 0)
							{
								AllFeaturedMatixList =  S.swtExtract(m+1,EnhancedDataMatrixlist);
								levelswtFeaturedMatixList.add(AllFeaturedMatixList);
							}
						}
					
				// pca

				ReductionDeminsion_PCA RDP = new ReductionDeminsion_PCA();
				ReducePCANeural NNP = new ReducePCANeural();						
						
				if(levelswtFeaturedMatixList.size() > 0)
				{
				  try {
					FinalUsertestfeatures   = RDP.reducefeatures(levelswtFeaturedMatixList, x - 1);
					neuralClassifyData  = NNP.reducefeatures(levelswtFeaturedMatixList, x-1);
				} catch (MWException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				}
							

			    //System.out.print("");
					
				///////// pca from train button at training tool
				/*
				
				
				
					
						KLDANeuralPCA Kll = new KLDANeuralPCA();
					//	Kll.classifykernalplusdistance(FinalNeurallearnfeatures, FinalNerualtextfeatures);
					
					  classifyData = Kll.gttestedred();
						
				
				
				*/
				
				////////
				
				
				
				String st="Load is done!";
				JOptionPane.showMessageDialog(null,st);  	
				
				


			}
		});
		mnNewMenu.add(mntmOpenFolder);

		JSeparator separator = new JSeparator();
		mnNewMenu.add(separator);

		JMenuItem mntmSaveAs = new JMenuItem("Save as");
		mntmSaveAs.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				final JFileChooser saveFile = new JFileChooser();
			      int actionDialog = saveFile.showSaveDialog(null);
			      if (actionDialog != JFileChooser.APPROVE_OPTION) {
			         return;
			      }

			      File fileName = new File(saveFile.getSelectedFile() + ".txt");
			      BufferedWriter outFile = null;
			      try {
			         outFile = new BufferedWriter(new FileWriter(fileName));

			         resultTextArea.write(outFile); 

			      } catch (IOException ex) {
			         ex.printStackTrace();
			      } finally {
			         if (outFile != null) {
			            try {
			               outFile.close();
			            } catch (IOException e1) {
			            
			            }
			         }
				
				
			}
			}});
		mnNewMenu.add(mntmSaveAs);

		JSeparator separator_1 = new JSeparator();
		mnNewMenu.add(separator_1);

		JMenuItem mntmExit = new JMenuItem("Exit");
		mntmExit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				System.exit(0);
			}
		});
		mnNewMenu.add(mntmExit);

		JMenu mnClassify = new JMenu("Classify");
		menuBar.add(mnClassify);

		JMenuItem mntmEucladianDistanceClassifier = new JMenuItem("Eucladian Distance  classifier");
		mntmEucladianDistanceClassifier.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
UserClassification UC = new UserClassification();
				
				try {
					String [] result = UC.classify(FinalUsertestfeatures);
					for(int i = 0; i < result.length ; i++)
					{
				      	resultTextArea.append(result[i]);
					}
				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (MWException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		mnClassify.add(mntmEucladianDistanceClassifier);

		JMenuItem mntmNeuralNetworkClassifier = new JMenuItem("Neural Network classifier");
		mntmNeuralNetworkClassifier.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				UserClassification UC = new UserClassification();
				
				try {
					String [] result = UC.neuralClassify(neuralClassifyData);
					for(int i = 0; i < result.length ; i++)
					{
				      	resultTextArea.append(result[i]);
					}
				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (MWException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

			
			}
		});
		mnClassify.add(mntmNeuralNetworkClassifier);

		JMenu mnHelp = new JMenu("Help");
	
		
		
		menuBar.add(mnHelp);

		JMenuItem mntmAbout = new JMenuItem("About");
		mntmAbout.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				Object message = "JDetector is an application for classifcation of tumors in MRI brain images.";
				JOptionPane.showMessageDialog(getComponent(0), message);
				
			}
			
			
		});
		mnHelp.add(mntmAbout);

		JMenuItem mntmHelp = new JMenuItem("Help");
		mntmHelp.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Object message = " Please contact asaber84@gmail.com or nhasan@eelu.edu.eg for any inquiries.";
				JOptionPane.showMessageDialog(getComponent(0), message);
				
			}
		});
		mnHelp.add(mntmHelp);

		contentPane = new JPanel();
		contentPane.setToolTipText("");
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		
		final JTextArea resultTextArea = new JTextArea();
		resultTextArea.setBackground(UIManager.getColor("Panel.background"));
		resultTextArea.setEditable(false);

		JPanel panel = new JPanel();
		panel.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));

		final JButton btnLoadFolderOf = new JButton("Load folder");
		btnLoadFolderOf.setToolTipText("Load folder of MRI images to be classified");
//		final String fileNames;

		final JPanel panel_2 = new JPanel();
		





		

		//JButton btnLoadFolderOf = new JButton("Load folder");
		//btnLoadFolderOf.setToolTipText("Load folder of MRI images to be classified");
		btnLoadFolderOf.addActionListener(new ActionListener() {


			JFileChooser folderChoose = new JFileChooser();
			public void actionPerformed(ActionEvent e) {
				//btnLoadImage.setEnabled(false);;

				folderChoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				folderChoose.showOpenDialog(null);
				final String folderName = folderChoose.getSelectedFile().getPath();
				File folder = new File(folderName);
				final File[] listOfFiles = folder.listFiles();



				folderList.addListSelectionListener(
						new ListSelectionListener() {

							@Override
							public void valueChanged(ListSelectionEvent arg0) {

								File f = new File(folderName, folderList.getSelectedValue());
								final ImageIcon originalIcon = new ImageIcon(f.getPath());
//								BufferedImage destinationImage = new BufferedImage(previewPanel.getWidth(), previewPanel.getHeight(), BufferedImage.TYPE_INT_RGB);
//								destinationImage.getGraphics().drawImage(originalIcon.getImage(), 0, 0, panel_2.getWidth(), prevpanel_2.getHeight(), null);
////										previewImageLabel.setIcon(new ImageIcon(destinationImage));
								previewPanel.image=originalIcon.getImage();
								previewPanel.repaint();
							}
						});




				for (int i = 0; i < listOfFiles.length; i++) {
					if (listOfFiles[i].isFile()) {

						model.addElement(listOfFiles[i].getName());

						//fileNames[i] = listOfFiles[i].getName();

						//folderTextArea.append(listOfFiles[i].getName() + "\n");
						//previewLabel.setIcon(new ImageIcon(listOfFiles[i].getPath()));
						//String[] fileNames 
					}

				}
				
				final int listModelSize = folderList.getModel().getSize();
				if(listModelSize !=0){
					folderList.setSelectedIndex(0);
				}
				btnLoadFolderOf.setEnabled(listModelSize ==0);
				
				int filesNumber = listOfFiles.length;
				String loadedData = new String("The number of loaded files is: " + filesNumber);
				resultTextArea.append(loadedData + "\n");
				

				//model.addElement(fileNames);



				


				LoadData ld = new LoadData();
				AMatrix[] InputDataMatrix = null;
				InputDataMatrix = ld.loadInputdata(folderName);
				
				
				Enhance E = new Enhance();
				for(int k = 0; k < InputDataMatrix.length ; k++)
				{
					inputDataMatixList.add(InputDataMatrix[k]);
				}

				ArrayList<AMatrix> EnhancedDataMatrixlist  = E.ApplyEnhance(inputDataMatixList);

				//SWT

				
				ArrayList<FeatureExtraction> AllFeaturedMatixList = new ArrayList<FeatureExtraction>(); 
				
					swtFExtraction S = new swtFExtraction();
					int x = 3;
					for(int m = 0; m <  x; m++){
						


							if(EnhancedDataMatrixlist.size() > 0)
							{
								AllFeaturedMatixList =  S.swtExtract(m+1,EnhancedDataMatrixlist);
								levelswtFeaturedMatixList.add(AllFeaturedMatixList);
							}
						}
					
				// pca

				ReductionDeminsion_PCA RDP = new ReductionDeminsion_PCA();
				ReducePCANeural NNP = new ReducePCANeural();						
						
				if(levelswtFeaturedMatixList.size() > 0)
				{
				  try {
					FinalUsertestfeatures   = RDP.reducefeatures(levelswtFeaturedMatixList, x - 1);
					neuralClassifyData  = NNP.reducefeatures(levelswtFeaturedMatixList, x-1);
				} catch (MWException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				}
							

			    //System.out.print("");
					
				///////// pca from train button at training tool
				/*
				
				
				
					
						KLDANeuralPCA Kll = new KLDANeuralPCA();
					//	Kll.classifykernalplusdistance(FinalNeurallearnfeatures, FinalNerualtextfeatures);
					
					  classifyData = Kll.gttestedred();
						
				
				
				*/
				
				////////
				
				
				
				String st="Load is done!";
				JOptionPane.showMessageDialog(null,st);  	
				
				


			}
		});    




		JButton btnClassify = new JButton("Classify by Neural Network");
		btnClassify.addActionListener(new ActionListener() {
		
				
				public void actionPerformed(ActionEvent e) {
					
					UserClassification UC = new UserClassification();
					
					try {
						String [] result = UC.neuralClassify(neuralClassifyData);
						for(int i = 0; i < result.length ; i++)
						{
					      	resultTextArea.append(result[i]);
						}
					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (MWException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

				
					
			}
		});

		JButton btnClassifyByEucladian = new JButton("Classify by Eucladian distance");
		btnClassifyByEucladian.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				UserClassification UC = new UserClassification();
				
				try {
					String [] result = UC.classify(FinalUsertestfeatures);
					for(int i = 0; i < result.length ; i++)
					{
				      	resultTextArea.append(result[i]);
					}
				} catch (FileNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} catch (MWException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}
		});

		JPanel panel_3 = new JPanel();

		JPanel panel_1 = new JPanel();
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addComponent(panel_3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addGroup(gl_contentPane.createSequentialGroup()
							.addComponent(panel, GroupLayout.PREFERRED_SIZE, 274, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(panel_1, GroupLayout.DEFAULT_SIZE, 403, Short.MAX_VALUE)))
					.addContainerGap())
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false)
						.addComponent(panel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addComponent(panel_1, GroupLayout.DEFAULT_SIZE, 227, Short.MAX_VALUE))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(panel_3, GroupLayout.PREFERRED_SIZE, 292, GroupLayout.PREFERRED_SIZE)
					.addContainerGap())
		);
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addGap(10)
					.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
						.addComponent(btnClassify, GroupLayout.PREFERRED_SIZE, 248, GroupLayout.PREFERRED_SIZE)
						.addComponent(btnClassifyByEucladian, GroupLayout.PREFERRED_SIZE, 248, GroupLayout.PREFERRED_SIZE)))
				.addGroup(Alignment.TRAILING, gl_panel.createSequentialGroup()
					.addContainerGap()
					.addComponent(btnLoadFolderOf, GroupLayout.PREFERRED_SIZE, 248, GroupLayout.PREFERRED_SIZE)
					.addGap(12))
		);
		gl_panel.setVerticalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addContainerGap()
					.addComponent(btnLoadFolderOf, GroupLayout.PREFERRED_SIZE, 42, GroupLayout.PREFERRED_SIZE)
					.addGap(11)
					.addComponent(btnClassify, GroupLayout.PREFERRED_SIZE, 38, GroupLayout.PREFERRED_SIZE)
					.addGap(11)
					.addComponent(btnClassifyByEucladian, GroupLayout.PREFERRED_SIZE, 41, GroupLayout.PREFERRED_SIZE))
		);
		panel.setLayout(gl_panel);


		panel_2.setBorder(new TitledBorder(null, "Preview", TitledBorder.LEFT, TitledBorder.TOP, null, null));
		panel_2.setLayout(new GridLayout(0, 1, 0, 0));


		folderList.setBackground(UIManager.getColor("Panel.background"));
		scrollPane.setViewportView(folderList);
		GroupLayout gl_panel_1 = new GroupLayout(panel_1);
		gl_panel_1.setHorizontalGroup(
			gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_1.createSequentialGroup()
					.addContainerGap()
					.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 58, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addComponent(panel_2, GroupLayout.PREFERRED_SIZE, 315, GroupLayout.PREFERRED_SIZE)
					.addContainerGap())
		);
		gl_panel_1.setVerticalGroup(
			gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(Alignment.TRAILING, gl_panel_1.createSequentialGroup()
					.addGap(11)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.TRAILING)
						.addComponent(scrollPane, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE)
						.addComponent(panel_2, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE))
					.addContainerGap())
		);
		
		panel_2.add(previewPanel);




		//panel_2.add(previewImageLabel);
		panel_1.setLayout(gl_panel_1);

	
		JButton btnSaveResults_1 = new JButton("Save results");
		btnSaveResults_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
			     final JFileChooser saveFile = new JFileChooser();
			      int actionDialog = saveFile.showSaveDialog(null);
			      if (actionDialog != JFileChooser.APPROVE_OPTION) {
			         return;
			      }

			      File fileName = new File(saveFile.getSelectedFile() + ".txt");
			      BufferedWriter outFile = null;
			      try {
			         outFile = new BufferedWriter(new FileWriter(fileName));

			         resultTextArea.write(outFile); 

			      } catch (IOException ex) {
			         ex.printStackTrace();
			      } finally {
			         if (outFile != null) {
			            try {
			               outFile.close();
			            } catch (IOException e1) {
			            
			            }
			         }
				
				
				
			}
		}});

		JLabel lblResults = new JLabel("Results");
		GroupLayout gl_panel_3 = new GroupLayout(panel_3);
		gl_panel_3.setHorizontalGroup(
				gl_panel_3.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panel_3.createSequentialGroup()
						.addGroup(gl_panel_3.createParallelGroup(Alignment.TRAILING)
								.addComponent(resultTextArea, GroupLayout.DEFAULT_SIZE, 677, Short.MAX_VALUE)
								.addGroup(gl_panel_3.createSequentialGroup()
										.addContainerGap()
										.addComponent(lblResults, GroupLayout.PREFERRED_SIZE, 256, GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(ComponentPlacement.RELATED, 320, Short.MAX_VALUE)
										.addComponent(btnSaveResults_1)))
										.addContainerGap())
				);
		gl_panel_3.setVerticalGroup(
				gl_panel_3.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_3.createSequentialGroup()
						.addGroup(gl_panel_3.createParallelGroup(Alignment.BASELINE)
								.addComponent(btnSaveResults_1)
								.addComponent(lblResults, GroupLayout.PREFERRED_SIZE, 18, GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(ComponentPlacement.RELATED)
								.addComponent(resultTextArea, GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE))
				);
		panel_3.setLayout(gl_panel_3);
		contentPane.setLayout(gl_contentPane);






	}
}